package net.lzzy.practices.web;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import net.lzzy.practices.constants.ApiConstants;
import net.lzzy.practices.constants.Messages;
import net.lzzy.practices.entities.User;
import net.lzzy.practices.service.UserService;
import net.lzzy.practices.utils.AuthUtils;
import net.lzzy.practices.utils.FileUtils;
import net.lzzy.practices.utils.StringUtils;
import net.lzzy.practices.web.models.ApiResult;
import net.lzzy.practices.web.models.LoginInfo;
import net.lzzy.practices.web.models.RegisterInfo;
import net.lzzy.practices.web.models.VmUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.UUID;

/**
 * @author 渊何
 */
@Api(tags = "用户认证")
@CrossOrigin
@RestController
@RequestMapping(ApiConstants.ROUTE_AUTH_ROOT)
public class AuthApiController {
    private final UserService service;
    @Value("${user.pic}")
    private String imgPath;

    @Autowired
    public AuthApiController(UserService service) {
        this.service = service;
    }

    @ApiOperation(value = "用户登录", notes = "<b>参数包括：</b><br/>&nbsp;&nbsp;&nbsp;&nbsp;用户名和密码")
    @ApiImplicitParam(name = "json", value = "登录信息", dataType = "LoginInfo", dataTypeClass = LoginInfo.class,
            paramType = "body", required = true)
    @PostMapping(value = ApiConstants.ROUTE_AUTH_LOGIN, produces = ApiConstants.API_PRODUCES_JSON)
    public ApiResult login(@RequestBody LoginInfo json) {
        String userName = json.getUsername();
        String password = json.getPassword();
        String salt = service.getSalt(userName);
        User user = service.check(userName, StringUtils.md5Encode(password, salt));
        if (user == null) {
            return new ApiResult(false, Messages.WRONG_PASSWORD.toString(), null);
        }
        if (user.getType() < 0) {
            return new ApiResult(false, Messages.USER_FORBIDDEN.toString(), null);
        }
        VmUser vmUser = VmUser.apiLogin(user);
        return new ApiResult(true, Messages.SUCCESS.toString(), vmUser);
    }

    @ApiOperation(value = "用户注销", notes = "<b>参数包括：</b><br/>&nbsp;&nbsp;&nbsp;&nbsp;token值")
    @PostMapping(ApiConstants.ROUTE_AUTH_LOGOUT)
    public ApiResult logout(@RequestParam String token) {
        return new ApiResult(true, AuthUtils.logout(token), null);
    }

    @ApiOperation(value = "用户是否存在", notes = "<b>参数包括：</b><br/>&nbsp;&nbsp;&nbsp;&nbsp;用户名")
    @GetMapping(ApiConstants.ROUTE_AUTH_EXISTS)
    public ApiResult isUserExists(@PathVariable String user) {
        boolean exists = service.isUserNameOccupied(user);
        return new ApiResult(true, exists ? "用户名已被占用!" : "", exists);
    }

    @ApiOperation(value = "用户注册", notes = "<b>参数包括：" + "</b><br/>1.nick(String)<br/>2.user(String)<br/>3.phone(String)<br/>" +
            "4.avatar(String)<br/>5.email(String)<br/>6.password(String)<br/>7.apply(boolean)<br/>")
    @PostMapping(ApiConstants.ROUTE_AUTH_REGISTER)
    public ApiResult register(@RequestBody RegisterInfo info) {
        String nick = info.getNick();
        String user = info.getUser();
        String phone = info.getPhone();
        String avatar = info.getAvatar();
        String email = info.getEmail();
        String password = info.getPassword();
        boolean apply = info.isApply();
        String salt = UUID.randomUUID().toString();
        if (StringUtils.isEmpty(nick) ||
                StringUtils.isEmpty(user) ||
                StringUtils.isEmpty(phone) ||
                StringUtils.isEmpty(avatar) ||
                StringUtils.isEmpty(email) ||
                StringUtils.isEmpty(password)) {
            return new ApiResult(false, Messages.INCOMPLETE_INFO.toString(), null);
        }
        //phone,email格式验证，正则表达式
        if (service.isUserNameOccupied(user)) {
            return new ApiResult(false, "用户名已被占用!", null);
        }
        User usr = new User();
        usr.setApplyTeacher(apply);
        usr.setType(User.TYPE_STUDENT);
        usr.setAvatar(avatar);
        usr.setEmail(email);
        usr.setPhone(phone);
        usr.setNickName(nick);
        usr.setPassword(StringUtils.md5Encode(password, salt));
        usr.setSalt(salt);
        usr.setUserName(user);
        VmUser vmUser = VmUser.apiLogin(service.register(usr));
        return new ApiResult(true, "注册成功", vmUser);
    }

    @ApiOperation(value = "上传文件", notes = "<b>参数包括：</b><br/>&nbsp;&nbsp;&nbsp;&nbsp;文件名String")
    @PostMapping(ApiConstants.ROUTE_AUTH_UPLOAD)
    public ApiResult upload(@RequestParam MultipartFile file) {
        String result = FileUtils.upload(file, imgPath);
        boolean success = result.length() > 0;
        return new ApiResult(success,
                success ? "上传成功" : "上传失败！",
                result);
    }
}
